<?php

namespace app\admin\controller\helper;

use app\common\controller\Backend;
use fast\Tree;

/**
 * 菜单管理
 *
 * @icon   fa fa-th
 */
class Menu extends Backend
{
    protected $model = null;
    protected $rulelist = [];
    protected $menuList = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\AuthRule;
        // 必须将结果集转换为数组
        $ruleList = collection($this->model->where('ismenu', 1)->where('id','<>',1)->where('status', 'normal')->field('condition,remark,createtime,updatetime', true)->order('weigh DESC,id ASC')->select())->toArray();
        foreach ($ruleList as $k => &$v) {
            $v['title'] = __($v['title']);
        }
        unset($v);
        $menuList = get_addon_config('helper')['MenuList'];
        $this->menuList = explode(',', $menuList);
        Tree::instance()->init($ruleList);
        $this->rulelist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'title');
        foreach ($this->rulelist as $k => &$v) {
            $v['isshow'] = in_array($v['id'],$this->menuList);
        }
        unset($v);
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $list = $this->rulelist;
            $total = count($this->rulelist);

            $result = array('total' => $total, 'rows' => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function multi($ids = '')
    {
        $ids = $ids ? $ids : $this->request->param('ids');
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post('params'), $values);
                if (isset($values['isshow'])) {
                    $ids = explode(',',$ids);
                    $ids = $values['isshow'] ? array_unique(array_merge($ids,$this->menuList)) : array_diff($this->menuList,$ids);

                    $result = set_addon_config('helper', ['MenuList' => implode(',',$ids)]);
                    if ($result) {
                        $this->success();
                    } else {
                        $this->error();
                    }
                }
            }
        }
    }
}
